package org.hy.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

/**
 * @author hy
 * @date 2025-02-26
 **/
public class DruidUtil {

    private static DataSource dataSource;

    public static DataSource getDataSource(){
        if (dataSource == null){
            initDataSource();
        }
        return dataSource;
    }

    private static void initDataSource(){
        Properties prop = new Properties();
        try {
            prop.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (Exception e) {
            throw new RuntimeException("获取连接对象失败");
        }
    }

    public static void close(Connection conn){
        if (conn != null){
            try {
                conn.close();
            } catch (Exception e) {
                throw new RuntimeException("关闭连接对象失败");
            }
        }
    }
}
